package com.macro.mall.common.util;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * Spring工具
 *
 * @author xuyanjun
 * @date 2019-06-28
 */
public class SpringUtils implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext appContext) throws BeansException {
        applicationContext = appContext;
    }

    /**
     * 根据class获取bean
     *
     * @param clazz clazz
     * @param <T>   类型
     * @return bean
     */
    public static <T> T getBean(Class<T> clazz) {
        return applicationContext.getBean(clazz);
    }

    /**
     * 根据beanName获取bean
     *
     * @param beanName beanName
     * @return bean
     */
    public static Object getBean(String beanName) {
        String[] names = applicationContext.getBeanDefinitionNames();
        for (String name : names) {
            if (name.equalsIgnoreCase(beanName)) {
                return applicationContext.getBean(name);
            }
        }
        return null;
    }
}
